<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域，搜索框 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-input
            placeholder="请输入搜索内容"
            v-model="queryInfo.query"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList()"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="dialogVisible = true"
            >添加用户</el-button
          >
          <!-- 添加用户的对话框 -->
          <el-dialog
            title="添加用户"
            :visible.sync="dialogVisible"
            width="50%"
            @close="addHandleClose"
          >
            <!-- 添加用户信息对话框的表单区域 -->
            <el-form
              :model="addForm"
              status-icon
              :rules="addFormRules"
              ref="addFormRef"
              label-width="70px"
              label-position="left"
            >
              <el-form-item label="用户名" prop="username">
                <el-input v-model="addForm.username"></el-input>
              </el-form-item>
              <el-form-item label="密码" prop="password">
                <el-input
                  v-model="addForm.password"
                  type="password"
                  show-password
                ></el-input>
              </el-form-item>
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="addForm.email"></el-input>
              </el-form-item>
              <el-form-item label="电话" prop="mobile">
                <el-input v-model.number="addForm.mobile"></el-input>
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="dialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="adduser">确 定</el-button>
            </span>
          </el-dialog>
        </el-col>
      </el-row>
      <div>
        <!-- 用户信息的表格区域 -->
        <el-table :data="userList" style="width: 100%" border stripe>
          <el-table-column type="index" label="#" width="40"></el-table-column>
          <el-table-column
            prop="username"
            label="姓名"
            width="100"
          ></el-table-column>
          <el-table-column
            prop="email"
            label="邮箱"
            width="260"
          ></el-table-column>
          <el-table-column
            prop="mobile"
            label="电话"
            width="180"
          ></el-table-column>
          <el-table-column
            prop="role_name"
            label="角色"
            width="180"
          ></el-table-column>
          <el-table-column label="状态" width="140">
            <template v-slot:default="scope">
              <!-- 通过scope.row可以获取(表格)这一行的数据，这个插槽不太懂，文档没看明白 -->
              <el-switch
                v-model="scope.row.mg_state"
                @change="userStateChange(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <!-- 操作列里面的三个按钮 -->
            <template v-slot:default="scope">
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="small"
                @click="showEditDialog(scope.row.id)"
              ></el-button>
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="small"
                @click="removeUserById(scope.row.id)"
              ></el-button>
              <el-tooltip
                effect="light"
                content="分配角色"
                placement="top"
                :hide-after="500"
                :enterable="false"
              >
                <el-button
                  type="warning"
                  icon="el-icon-setting"
                  size="small"
                  @click="setRoles(scope.row)"
                ></el-button>
              </el-tooltip>
              <!-- 修改用户信息的对话框 -->
              <el-dialog
                title="修改用户信息"
                :visible.sync="editDialogFormVisible"
                width="50%"
                @close="editHandleClose"
              >
                <el-form
                  :model="editForm"
                  status-icon
                  :rules="editFormRules"
                  ref="editFormRef"
                  label-position="left"
                  label-width="70px"
                >
                  <el-form-item label="用户名">
                    <el-input
                      v-model="editForm.username"
                      :disabled="true"
                    ></el-input>
                  </el-form-item>
                  <el-form-item label="邮箱" prop="email">
                    <el-input v-model="editForm.email"></el-input>
                  </el-form-item>
                  <el-form-item label="手机" prop="mobile">
                    <el-input v-model.number="editForm.mobile"></el-input>
                  </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                  <el-button @click="editDialogFormVisible = false"
                    >取 消</el-button
                  >
                  <el-button type="primary" @click="editUser()"
                    >确 定</el-button
                  >
                </div>
              </el-dialog>
              <!-- 给用户分配角色的弹出式对话框 -->
              <el-dialog
                title="分配角色"
                :visible.sync="setRolesDialogVisiable"
                width="50%"
                @close="setRolesDialogClose"
              >
                <div>
                  <p>当前的用户: {{ userInfo.username }}</p>
                  <p>当前的角色: {{ userInfo.role_name }}</p>
                  <p>
                    分配新的角色:
                    <el-select
                      v-model="seleteRolesId"
                      placeholder="请选择"
                      clearable
                    >
                      <el-option
                        v-for="item in rolesList"
                        :key="item.id"
                        :label="item.roleName"
                        :value="item.id"
                      >
                      </el-option>
                    </el-select>
                  </p>
                </div>
                <span slot="footer">
                  <el-button @click="setRolesDialogVisiable = false"
                    >取 消</el-button
                  >
                  <el-button type="primary" @click="saveRoleInfo()"
                    >确 定</el-button
                  >
                </span>
              </el-dialog>
            </template>
          </el-table-column>
        </el-table>
        <!-- 下面分页显示的条条 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="queryInfo.pagesize"
          :current-page="queryInfo.pagenum"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  data () {
    // 自定义校验规则，验证邮箱和手机号格式
    var checkemail = (rule, value, callback) => {
      const regEmail = /^[a-z0-9A-Z_-]+@([a-z0-9A-Z_-])+(\.[a-z0-9A-Z_-])+/
      if (regEmail.test(value)) {
        return callback()
      } else {
        return callback(new Error('邮箱格式不合法'))
      }
    }
    var checkmobile = (rule, value, callback) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        return callback()
      } else {
        return callback(new Error('手机号格式不合法'))
      }
    }
    return {
      userList: [],
      //  总用户数量
      total: 0,
      queryInfo: {
        query: '',
        // 当前页码
        pagenum: 1,
        // 每页显示多少条数据
        pagesize: 10
      },
      // 对话框隐藏属性，默认隐藏,1添加用户2修改用户信息
      dialogVisible: false,
      editDialogFormVisible: false,
      setRolesDialogVisiable: false,
      // 添加用户的表单数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 添加用户表单的验证规则对象
      addFormRules: {
        username: [
          { required: true, message: '用户名不能为空', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '邮箱不能为空', trigger: 'blur' },
          { validator: checkemail, rigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          { validator: checkmobile, trigger: 'blur' }
        ]
      },
      // 修改用户信息通过id查询到的用户数据
      editForm: {},
      // 添加用户表单的验证规则对象
      editFormRules: {
        email: [
          { required: true, message: '邮箱不能为空', trigger: 'blur' },
          { validator: checkemail, rigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          { validator: checkmobile, trigger: 'blur' }
        ]
      },
      // 分配角色对话框要使用的数据，存放当前用户的信息里面的是用户id，注意和角色Id区分
      userInfo: {},
      // 角色列表，分配角色时候要用
      rolesList: [],
      // 被选中的角色ID
      seleteRolesId: ''
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    // 获取用户列表数据
    async getUserList () {
      const { data: res } = await this.$http.get('/users', { params: this.queryInfo })
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败！')
      } else {
        // console.log(res)
        this.total = res.data.total
        this.userList = res.data.users
      }
    },
    // pagesize改变事件,每页显示条数更改
    handleSizeChange (newPageSize) {
      this.queryInfo.pagesize = newPageSize
      this.getUserList()
    },
    // pagenum改变事件，当前页码修改
    handleCurrentChange (newPageNum) {
      this.queryInfo.pagenum = newPageNum
      this.getUserList()
    },
    async userStateChange (userinfo) {
      // 模板字符串中嵌入变量，需要将变量名写在${}之中，新知识点，之前没了解过
      const { data: res } = await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state
        this.$message.error('更新用户状态失败！' + res.meta.msg + ' 错误码：' + res.meta.status)
      }
    },
    // 修改用户的对话框关闭之前调用的Methods
    addHandleClose () {
      // 重置表单
      this.$refs.addFormRef.resetFields()
    },
    // 点击确认按钮，添加新用户
    adduser () {
      this.$refs.addFormRef.validate(async valid => {
        if (valid) {
          // 校验通过，可以发送添加用户的请求
          const { data: res } = await this.$http.post('users', this.addForm)
          if (res.meta.status === 201) {
            this.$message.success(res.meta.msg + '!')
            this.getUserList()
          } else {
            this.$message.error(res.meta.msg + '!')
          }
          this.dialogVisible = false
        } else {
          this.$message.error('数据校验失败！')
          return false
        }
      })
    },
    async showEditDialog (id) {
      this.editDialogFormVisible = true
      const { data: res } = await this.$http.get(`users/${id}`)
      if (res.meta.status === 200) {
        this.editForm = res.data
      } else {
        this.$message.error(res.meta.msg + res.meta.status)
        return false
      }
    },
    // 重置編輯用戶信息對話框
    editHandleClose () {
      this.$refs.editFormRef.resetFields()
    },
    // 编辑按钮，修改用户信息
    editUser () {
      this.$refs.editFormRef.validate(async valid => {
        if (valid) {
          // 校验通过，可以发送添加用户的请求
          const { data: res } = await this.$http.put(`users/${this.editForm.id}`,
            { email: this.editForm.email, mobile: this.editForm.mobile })
          if (res.meta.status === 200) {
            this.$message.success(res.meta.msg + '!')
            this.getUserList()
          } else {
            this.$message.error(res.meta.msg + '!')
          }
          this.editDialogFormVisible = false
        } else {
          this.$message.error('数据校验失败！')
          return false
        }
      })
    },
    // 通过点击删除按钮删除单条用户信息
    removeUserById (id) {
      this.$MessageBox.confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(async () => {
        // 发送请求，进行删除用户操作
        const { data: res } = await this.$http.delete(`users/${id}`)
        if (res.meta.status === 200) {
          this.$message.success('删除成功!')
          this.getUserList()
        } else {
          // 删除失败
          this.$message.error(res.meta.msg)
          return false
        }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    // 分配角色的对话框
    async setRoles (userInfo) {
      this.userInfo = userInfo
      // 在展示对话框之前获取角色列表
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status === 200) {
        this.rolesList = res.data
      } else {
        return this.$message.error(res.meta.msg)
      }
      this.setRolesDialogVisiable = true
    },
    // 关闭分配角色对话框
    setRolesDialogClose () {
      this.userInfo = []
      this.seleteRolesId = ''
    },
    // 分配角色对话框，点击确认按钮
    async saveRoleInfo () {
      if (!this.seleteRolesId) {
        return this.$message.error('请选择要分配的角色！')
      }
      // 发起分配用户角色请求
      const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`, { rid: this.seleteRolesId })
      if (res.meta.status === 200) {
        this.$message.success(res.meta.msg)
        this.setRolesDialogVisiable = false
        this.getUserList()
      } else {
        return this.$message.error(res.meta.msg)
      }
    }
  }
}
</script>
<style lang="less" scoped>
</style>
